﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Crawler_v1.entity;
using Crawler_v1.service;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.IO;
using System.Threading;
using Crawler_v1.utils;
using Newtonsoft.Json;

namespace Crawler_v1.ui
{
    partial class MainForm
    {
        public const string POST_URL = "http://192.168.1.225:9202/baiduWebupload/testServer.php";
        private PageInfo pageInfo;
        private ArticleService service;

        /// <summary>
        /// 初始化工作
        /// </summary>
        public void initDataGrid()
        {
            pageInfo = new PageInfo();
            pageInfo.CurPage = 1;
            pageInfo.Conditions = new Dictionary<string, string>();
            pageInfo.PageSize = 20;

            service = new ArticleService();

            //grid view动态改变宽度
            /*
            int totalWidth = myGridTable.Width;
            int size = myGridTable.Columns.Count;
            //int[] weight=new int[dataGrid.Columns.Count];
            for (int i = 0; i < size; i++)
            {
                myGridTable.Columns[i].Width = totalWidth / size;
            }
            */

            /* 初始化栏目数据 */
            var json = FileUtil.readText("columns2.json");
            List<Column> columns = JsonConvert.DeserializeObject<List<Column>>(json);

            /*
            foreach (Column column in columns)
            {
                //ComboBoxItem cbi2 = new ComboBoxItem();
                //cbi2.Text = "测试Test2";
                //cbi2.Value = "测试Value2";
                columnComboBox.Items.Add(column);
            }
            */

            columnComboBox.Items.AddRange(columns.ToArray());
            columnComboBox.SelectedIndex = 0;


            //全部
            ComboBoxItem item1 = new ComboBoxItem();
            item1.Text = "已经提交";
            item1.Value = "1";
            ComboBoxItem item2 = new ComboBoxItem();
            item2.Text = "未提交";
            item2.Value = "0";
            ispostComboBox.Items.Add(item1);
            ispostComboBox.Items.Add(item2);
            //已经提交（1）
            //未提交（0）
            ispostComboBox.SelectedIndex = 0;
        }

        /// <summary>
        /// 是否post下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ispostComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ispostComboBox.SelectedIndex == 0)
            {
                pageInfo.Conditions.Remove("ispost");

            }
            else
            {
                ComboBoxItem cbi = ispostComboBox.SelectedItem as ComboBoxItem;
                if (cbi != null)
                {
                    pageInfo.Conditions.Remove("ispost");
                    pageInfo.Conditions.Add("ispost", cbi.Value.ToString());
                    
                }
            }
        }

        /// <summary>
        /// 栏目下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void columnComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (columnComboBox.SelectedIndex == 0)
            {
                pageInfo.Conditions.Remove("column");

            }
            else
            {
                Column cbi = columnComboBox.SelectedItem as Column;
                if (cbi != null)
                {
                    pageInfo.Conditions.Remove("column");
                    pageInfo.Conditions.Add("column", cbi.text);
                }
            }
        }

        /// <summary>
        /// 搜索按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            pageInfo.Conditions.Remove("name");
            string search = textBoxSearch.Text;
            if (search != "")
            {
                pageInfo.Conditions.Add("name", search);
            }

            pageInfo.CurPage = 1;
            getList();
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void nextPage_Click(object sender, EventArgs e)
        {
            if (pageInfo.CurPage < pageInfo.TotalPage)
            {
                pageInfo.CurPage++;
                getList();
            }
            else
            {
                MessageBox.Show("已到最后一页");
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void prevPage_Click(object sender, EventArgs e)
        {
            if (pageInfo.CurPage > 1)
            {
                pageInfo.CurPage--;
                getList();
            }
            else
            {
                MessageBox.Show("已到第一页");
            }
        }

        /// <summary>
        /// 到最后一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void moveLast_Click(object sender, EventArgs e)
        {
            pageInfo.CurPage = pageInfo.TotalPage;
            getList();
        }

        /// <summary>
        /// 到第一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void moveFirst_Click(object sender, EventArgs e)
        {
            pageInfo.CurPage = 1;
            getList();
        }

        /// <summary>
        /// 刷新按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            getList();
        }

        private ProgressForm progressForm;
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpload_Click(object sender, EventArgs e)
        {
            new Thread(upload).Start();
        }


        private void onUploadProgress(DataRow row, int index)
        {
            this.BeginInvoke(new Action<DataRow, int>((row_p, index_p) =>
            {

                progressForm.metroProgressBar1.Value = index_p;
                progressForm.countLabel.Text = index_p + "/" + progressForm.metroProgressBar1.Maximum;
                progressForm.msgLabel.Text = "上传文章【" + row["my_title"] + "】成功";

            }), row, index);

        }

        /// <summary>
        /// 新开的线程上传
        /// </summary>
        public void upload()
        {
            //当前post的数量
            int index = 0;

            DataTable dataTable = service.findAllNotPost().DataTable;

            //初始化进度条
            int total = dataTable.Rows.Count;
            this.BeginInvoke(new Action<int>((totalCount) =>
            {
                progressForm = new ProgressForm();
                progressForm.Show();
                this.Enabled = false;
                progressForm.countLabel.Text = 0 + "/" + totalCount;
                progressForm.metroProgressBar1.Maximum = totalCount;
            }), total);

            foreach (DataRow row in dataTable.Rows)
            {
                string id = row["my_id"].ToString();
                string title = row["my_title"].ToString();
                string content = row["my_content"].ToString();
                string time = row["my_time"].ToString();
                string parent = row["my_parent"].ToString();

                string url = POST_URL;
                Encoding encoding = Encoding.GetEncoding("utf-8");
                //post参数
                IDictionary<string, string> parameters = new Dictionary<string, string>();
                parameters.Add("title", title);
                parameters.Add("content", content);
                parameters.Add("time", time);
                parameters.Add("parent", parent);

                HttpWebResponse response = HttpReqTest.CreatePostHttpResponse(url, parameters, encoding);

                //打印返回值  
                Stream stream = response.GetResponseStream();   //获取响应的字符串流  
                StreamReader sr = new StreamReader(stream); //创建一个stream读取流  
                string html = sr.ReadToEnd();   //从头读到尾，放到字符串html  
                Console.WriteLine(html);


                //数据库更新
                string sql = "update article set ispost='1' where id=" + id;
                int i = SQLiteHelper.ExecuteSql(sql);
                if (i > 0)
                {
                    index++;
                    onUploadProgress(row, index);
                }
                else
                {
                    Console.WriteLine("写入post状态失败");
                }

                Thread.Sleep(500);//防止post过快
            }

            //上传完成
            this.BeginInvoke(new Action(() =>
            {

                MessageBox.Show("上传完成");
                this.Enabled = true;

                progressForm.Hide();
                progressForm.Dispose();

            }));
        }

        private void getList()
        {

            service.list(pageInfo);

            totalPage.Text = pageInfo.TotalPage.ToString();
            curPage.Text = pageInfo.CurPage.ToString();
            totalItems.Text = "数量：" + pageInfo.TotalItem + "条";

            myGridTable.AutoGenerateColumns = false;

            bindingSource1.DataSource = pageInfo.DataTable;
            myGridTable.DataSource = bindingSource1;
            caiji_pager.BindingSource = bindingSource1;
        }
    }
}
